package kassiopeia.agent.io.ping;

import java.io.File;
import java.lang.management.ClassLoadingMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.management.RuntimeMXBean;
import java.lang.management.ThreadMXBean;
import kassiopeia.commons.AgentStatus;
import kassiopeia.commons.TaskSummary;
import kassiopeia.commons.VMSummary;
import kassiopeia.commons.io.Ping;

public class PingFactory {

    public static Ping getPing(String agentId, String jmxUrl, AgentStatus agentStatus, TaskSummary task) {
        Ping ping = new Ping(agentId);

        ping.setVmSummary(createVmSummary());
        ping.setTaskSummary(task);
        ping.setSourceId(agentId);
        ping.setAgentStatus(agentStatus);
        ping.setJmxUrl(jmxUrl);

        return ping;
    }

    private static VMSummary createVmSummary() {
        VMSummary vmSummary = new VMSummary();

        setVmSection(vmSummary);
        setOsSection(vmSummary);
        setHddSection(vmSummary);
        setThreadsSection(vmSummary);
        setClassesSection(vmSummary);
        setMemorySection(vmSummary);

        return vmSummary;
    }

    private static void setVmSection(VMSummary vmSummary) {
        RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();

        vmSummary.setVmName(bean.getVmName());
        vmSummary.setVmVendor(bean.getVmVendor());
        vmSummary.setVmVersion(bean.getVmVersion());

        vmSummary.setVmUptime(bean.getUptime());
    }

    private static void setOsSection(VMSummary vmSummary) {
        OperatingSystemMXBean bean = ManagementFactory.getOperatingSystemMXBean();

        vmSummary.setOsArch(bean.getArch());
        vmSummary.setOsName(bean.getName());
        vmSummary.setOsVersion(bean.getVersion());

        vmSummary.setAvailableProcessors(bean.getAvailableProcessors());
    }

    private static void setHddSection(VMSummary vmSummary) {
        File file = new File(".");

        vmSummary.setHddFreeSpace(file.getUsableSpace());
        vmSummary.setHddTotalSpace(file.getTotalSpace());
    }

    private static void setThreadsSection(VMSummary vmSummary) {
        ThreadMXBean bean = ManagementFactory.getThreadMXBean();

        vmSummary.setThreadCount(bean.getThreadCount());
        vmSummary.setPeakThreadCount(bean.getPeakThreadCount());
        vmSummary.setDaemonThreadCount(bean.getDaemonThreadCount());
    }

    private static void setClassesSection(VMSummary vmSummary) {
        ClassLoadingMXBean bean = ManagementFactory.getClassLoadingMXBean();

        vmSummary.setLoadedClassesCount(bean.getLoadedClassCount());
    }

    private static void setMemorySection(VMSummary vmSummary) {
        Runtime runtime = Runtime.getRuntime();

        vmSummary.setTotalMemory(runtime.totalMemory());
        vmSummary.setFreeMemory(runtime.freeMemory());
    }
}
